from fastapi import FastAPI, Depends, HTTPException
import uvicorn
from dependencies import get_db
from sqlalchemy.orm import Session
import schemas, crud
from typing import List

app = FastAPI()


@app.get("/")
async def home():
    return {"username": "hello world!"}


# 创建作者信息
@app.post("/author", response_model=schemas.Author)
def create_author(author: schemas.AuthorCreate, db: Session = Depends(get_db)):
    db_author = crud.get_author_by_username(db, author.username)
    if db_author:
        raise HTTPException(status_code=400, detail="author already exists")
    return crud.create_author(db, author)


# 获取所有作者
@app.get("/authors", response_model=List[schemas.Author])
def get_all_auth(db: Session = Depends(get_db)):
    return crud.get_all_author(db)


# 创建出版社
@app.post("/publisher", response_model=schemas.Publish)
def create_publish(publish: schemas.PublishCreate, db: Session = Depends(get_db)):
    db_publish = crud.get_publish_by_name(db, publish.name)
    print(db_publish)
    if db_publish:
        raise HTTPException(status_code=400, detail="publish already exists!")
    return crud.create_publish(db, publish)


# 获取所有作者
@app.get("/publishers", response_model=List[schemas.Publish])
def get_all_publishers(db: Session = Depends(get_db)):
    return crud.get_all_publish(db)


# 创建书籍信息
@app.post("/book/{author_id}", response_model=schemas.Book)
def create_book(author_id: int, publish_id_list: List[int], book: schemas.BookCreate, db: Session = Depends(get_db)):
    db_book = crud.get_book_by_title(db, book.title)
    if db_book:
        raise HTTPException(status_code=400, detail="book already exists!")
    return crud.create_book_by_author(db, book, author_id, publish_id_list)


# 获取所有的作者信息
@app.get("/books")
def get_all_books(db: Session = Depends(get_db)):
    return crud.get_all_books(db)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    uvicorn.run(app=app, host="127.0.0.1", port=8030)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
